/* The file is part of the Waff web framework.
 *
 * Copyright (c) 2011, Grzegorz Skorupa
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditionsare met:
 *
 * - Redistributions of source code must retain the above copyright notice, this list of conditions
 *   and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions
 *   and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * - Neither the name of the Grzegorz Skorupa nor the names of its contributors may be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package pl.org.waff;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;

//TODO: use UserManager class
/**
 *
 * @author greg
 */
public class WaffUser implements User {
    
    public static final String ADMIN_ROLE_NAME = "administrators";
    public final static String PROPERTIES_FILE_NAME = "/WEB-INF/conf/users.properties";
    private static final Logger log = Logger.getLogger(WaffUser.class.getName());
    private String name;
    private String email;
    private String password;
    private HashSet roles;
    private boolean adminrole;
    private boolean logged = false;
    private boolean registered = false;
    private String alias;
    
    public WaffUser() {
        setName("guest");
        setEmail("");
        setAlias("guest");
        setRoles(null);
        setLoggedIn(false);
        setRegistered(false);
    }
    
    public WaffUser(String newName, String newEmail) {
        name = newName;
        email = newEmail;
        setRoles(null);
        setLoggedIn(true);
        setAdminrole(false);
        setRegistered(false);
    }
    
    public WaffUser(String newName, String newEmail, String newRoles) {
        name = newName;
        email = newEmail;
        setRoles(newRoles);
        setLoggedIn(true);
        setAdminrole(false);
        setRegistered(false);
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the role
     */
    public HashSet getRoles() {
        return (HashSet) roles.clone();
    }

    /**
     * @param role the role to set
     */
    public void setRoles(String roles) {
        this.roles = new HashSet();
        if (null != roles) {
            StringTokenizer t = new StringTokenizer(roles, ",");
            String roleName;
            while (t.hasMoreTokens()) {
                roleName = t.nextToken();
                this.roles.add(roleName);
                if (ADMIN_ROLE_NAME.equals(roleName)) {
                    setAdminrole(true);
                }
            }
        }
    }

    /**
     * @return the logged
     */
    public boolean isLoggedIn() {
        return logged;
    }

    /**
     * @param logged the logged to set
     */
    public void setLoggedIn(boolean logged) {
        this.logged = logged;
        if (!logged) {
            setName("guest");
            setEmail("");
            setRoles(null);
            setAdminrole(false);
        }
    }
    
    public void setAdminrole(boolean role) {
        adminrole = role;
        if (role) {
            roles.add(ADMIN_ROLE_NAME);
        } else {
            roles.remove(ADMIN_ROLE_NAME);
        }
    }

    /**
     * @return the adminrole
     */
    public boolean isAdminrole() {
        return adminrole;
    }
    
    public boolean hasRole(String role) {
        return roles.contains(role);
    }

    /**
     * @return the registered
     */
    public boolean isRegistered() {
        return registered;
    }

    /**
     * @param registered the registered to set
     */
    public void setRegistered(boolean registered) {
        this.registered = registered;
    }
    
    /*
    public void load(ServletContext context) {
        Properties properties = new Properties();
        java.io.InputStream is = context.getResourceAsStream(PROPERTIES_FILE_NAME);
        try {
            properties.load(is);
        } catch (IOException e) {
            log.severe(e.getMessage());
        } catch (Exception e) {
            log.severe(e.getMessage());
        }
        int size=0;
        size=Integer.parseInt(properties.getProperty("users.count", "0"));
        String text;
        for(int i=1; i<=size; i++){
            text=properties.getProperty("user."+i+".name");
            if(text!=null&&this.name.equals(text)){
                text=properties.getProperty("user."+i+".password","");
                if(this.password.equals(text)){
                    setRoles(properties.getProperty("user."+i+".roles",""));
                    setEmail(properties.getProperty("user."+i+".email",""));
                    setRegistered(true);
                    setLoggedIn(true);
                    break;
                }
            }
        }
    }
    */
    
    public void save() {
    }
    
    public void register() {
        setRegistered(true);
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String toString(){
        StringBuffer sb=new StringBuffer("{");
        sb.append("name:");
        sb.append(getName());
        sb.append("alias:");
        sb.append(getAlias());
        sb.append(",email:");
        sb.append(getEmail());
        sb.append(",logged:");
        sb.append(isLoggedIn());
        sb.append(",roles:[");
        Iterator it=roles.iterator();
        while(it.hasNext()){
            sb.append((String)it.next());
            if(it.hasNext()){
                sb.append(",");
            }
        }
        sb.append("]");
        sb.append("}");
        return  sb.toString();
    }

    /**
     * @return the alias
     */
    public String getAlias() {
        return alias;
    }

    /**
     * @param alias the alias to set
     */
    public void setAlias(String alias) {
        this.alias = alias;
    }
}
